import { _decorator, Component, Layout, Node, Prefab, resources, SpriteFrame, instantiate, Sprite, Pool } from 'cc';
const { ccclass, property, requireComponent } = _decorator;

const replacement = new Map()
replacement.set('/', 'Slash')

@ccclass('UIImageLabel')
@requireComponent(Layout)
export class UIImageLabel extends Component {

    @property(Prefab)
    private numberPrefab: Prefab = null

    private layout: Layout = null

    private numPool: Pool<Node> = null

    private _numStr: string = ''

    public get numStr(): string {
        return this._numStr
    }

    public set numStr(v : string) {
        if (this._numStr === v) return
        this._numStr = v
        this.resetString()
    }
    
    onLoad() {

        this.layout = this.node.getComponent(Layout)

        this.numPool = new Pool((): Node => {
            const node = instantiate(this.numberPrefab)
            node.active = false
            return node
        }, 1, (node: Node) => {
            node.removeFromParent()
        })
    }

    private resetString() {
        this.clearString()
        const dir = 'ui/num/'
        resources.loadDir(dir, SpriteFrame, (err, assets) => {
            for (let i = 0; i < this.numStr.length; i++) {
                let char = this.numStr[i]
                if (replacement.has(char)) char = replacement.get(char)

                const path = dir + char + `/spriteFrame`
                const spriteFrame = resources.get(path, SpriteFrame)

                // 运用正常读取方式
                // const spritePrefab = instantiate(this.numberPrefab)
                // const sprite = spritePrefab.getComponent(Sprite)
                // sprite.spriteFrame = spriteFrame
                // this.node.addChild(spritePrefab)

                // 运用内存池的方式实现
                const node = this.numPool.alloc()
                if (node.parent === null) this.node.addChild(node)

                node.active = true
                node.setSiblingIndex(i)
                const sprite = node.getComponent(Sprite)
                sprite.spriteFrame = spriteFrame
            }

            // this.layout.updateLayout()
        })
    }

    private clearString() {
        for (const child of this.node.children) {
            child.active = false
            this.numPool.free(child)
        }
    }
}


